package models

import (
	"fmt"

	"gitee.com/zinface/go.youwant-platform/external/utils"
)

type FileUpload struct {
	Id       int    `gorm:"AUTO_INCREMENT"`
	FileName string `gorm:"size:50"`
	FileExt  string `gorm:"size:50"`
	Uuid     string `gorm:"size:50"`
}

// ---------------------------------------------------------------- GenerateRandomUUID

func GenerateFileUploadUUID() string {
	uuid := utils.GenerateRandomMd5()

	fus := FindFileUpload(uuid)
	if len(fus) > 0 {
		return GenerateFileUploadUUID()
	}
	return uuid
}

// ---------------------------------------------------------------- FileUpLoad

func FindFileUpload(uuid string) []FileUpload {
	var fu []FileUpload
	err := db.Where("uuid = ?", uuid).Find(&fu).Error
	if err != nil {
		return fu
	}
	return fu
}

func FindFileUploads() []FileUpload {
	var fus []FileUpload
	err := db.Find(&fus).Error
	if err != nil {
		fmt.Println("err:", err.Error())
	}
	return fus

}

func FindFileUploadUUID(uuid string) (*FileUpload, error) {
	var fu = &FileUpload{}
	err := db.Where("uuid = ?", uuid).First(fu).Error
	if err != nil {
		return nil, err
	}
	return fu, nil
}

// ----------------------------------------------------------------

func SaveFileUpload(fu *FileUpload) error {
	fmt.Println("准备存储:", fu)
	if err := db.Create(fu).Error; err != nil {
		return err
	}
	return nil
}

func DeleteFileUpload(fu *FileUpload) error {
	fmt.Println("准备删除:", fu)
	return db.Delete(fu).Error
}
